// Copyright (c) 2000 Just Objects B.V. <just@justobjects.nl>
// Distributable under LGPL license. See terms of license at gnu.org.

package nl.justobjects.pushlet.core;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * FIFO queue with guarded suspension.
 * <b>Purpose</b><br>
 * <p/>
 * <b>Implementation</b><br>
 * FIFO queue class implemented with circular array. The enQueue() and
 * deQueue() methods use guarded suspension according to a readers/writers
 * pattern, implemented with java.lang.Object.wait()/notify().
 * <p/>
 * <b>Examples</b><br>
 * <p/>
 * <br>
 *
 * @author Just van den Broecke - Just Objects &copy;
 * @version $Id: EventQueue.java,v 1.3 2007/11/23 14:33:07 justb Exp $
 */
public class EventQueue {

    public static final Event[] EVENTS = new Event[0];
    private BlockingQueue<Event> queue = null;
	
	public EventQueue() {
		this(8);
	}
	
	public EventQueue(int capacity) {
		queue = new ArrayBlockingQueue<Event>(capacity);
	}
	
	public boolean enQueue(Event item, long maxWaitTime) throws InterruptedException {
		if (maxWaitTime > 0)
			return queue.offer(item, maxWaitTime, TimeUnit.MILLISECONDS);
		queue.put(item);
		return true;
	}
	
	public boolean enQueue(Event item) throws InterruptedException {
		return enQueue(item, -1);
	}
	
	public Event deQueue(long maxWaitTime) throws InterruptedException {
		if (maxWaitTime > 0)
			return queue.poll(maxWaitTime, TimeUnit.MILLISECONDS);
		return queue.take();
	}
	
	public Event deQueue() throws InterruptedException {
		return deQueue(-1);
	}
	
	public Event[] deQueueAll(long maxWaitTime) throws InterruptedException {
		List<Event> events = new ArrayList<Event>(8);
		Event headEvent = null;
		if (maxWaitTime > 0)
			headEvent = queue.poll(maxWaitTime, TimeUnit.MILLISECONDS);
		else
			headEvent = queue.take();
		if (headEvent != null)
			events.add(headEvent);
		queue.drainTo(events);
		return events.toArray(EVENTS);
	}
}

/*
* $Log: EventQueue.java,v $
* Revision 1.3  2007/11/23 14:33:07  justb
* core classes now configurable through factory
*
* Revision 1.2  2005/02/21 11:50:46  justb
* ohase1 of refactoring Subscriber into Session/Controller/Subscriber
*
* Revision 1.1  2005/02/18 10:07:23  justb
* many renamings of classes (make names compact)
*
* Revision 1.6  2005/02/16 12:16:16  justb
* added support for "poll" mode
*
* Revision 1.5  2005/01/13 14:47:15  justb
* control evt: send response on same (control) connection
*
* Revision 1.4  2004/09/03 22:35:37  justb
* Almost complete rewrite, just checking in now
*
* Revision 1.3  2003/08/15 08:37:40  justb
* fix/add Copyright+LGPL file headers and footers
*
*
*/
